package com.example.recyclerview.utli;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.PopupWindow;

import androidx.annotation.LayoutRes;

public class PopupWindowUtils {

    public static View getView(Context context, @LayoutRes int resource) {
        return LayoutInflater.from(context).inflate(resource, null);
    }

    public static PopupWindow createPopupWindow(View view) {
        return createPopupWindow(view, false);
    }

    public static PopupWindow createPopupWindow(View view, boolean isInput) {
        PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (isInput) {
            //这一句代码至关重要，决定着弹出窗体后是否可以继续输入
            popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        } else {
            popupWindow.setFocusable(true);
        }
        popupWindow.setOutsideTouchable(true);
        return popupWindow;
    }

    public static void darkenBackground(Window window, Float alpha) {
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = alpha;
        window.setAttributes(lp);
    }

    public static int getMeasuredHeight(View view) {
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        return view.getMeasuredHeight();
    }

    public static int getMeasuredWidth(View view) {
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        return view.getMeasuredWidth();
    }

    /**
     * 在控件上方显示
     */
    public static void showUp(PopupWindow popupWindow, View parent, View view) {
        //获取需要在其上方显示的控件的位置信息
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        int x = (location[0] + parent.getWidth() / 2) - getMeasuredHeight(view);
        int y = location[1] - getMeasuredWidth(view);
        popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, x, y);
    }

}
